package kr.or.smardi.smardi_AScan.Scan;

import kr.or.smardi.smardi_AScan.*;
import kr.or.smardi.smardi_AScan.Device.*;
import kr.or.smardi.smardi_AScan.Help.*;
import kr.or.smardi.smardi_AScan.Record.*;
import kr.or.smardi.smardi_AScan.User.*;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;

public class AC_Scan_main extends Activity {

	ImageView tutorial_image = null;
	Button btn_check_connection = null;

	//상단 타이틀바
	RelativeLayout titleBar = null;
	ImageButton btn_TopLeft = null;
	ImageButton btn_TopRight = null;
	TextView txt_subTitle = null;
	
	//탭 메뉴
	LinearLayout tabMenu = null;
	ImageButton tab_measure = null;
	ImageButton tab_record = null;
	ImageButton tab_user = null;
	ImageButton tab_help = null;
	
	boolean isTimerRun = false;
	
	/**
	 * Epi가 꽂힌 상태를 나타내기 위한 변수 headSetState 0: 뽑혔을 때 1: 꽂혀있을 때
	 */
	int headSetState = 0;
	int hasMicrophone = 0;

	Vibrator vibe = null;
	
	
	//나가기
	long lastBackPressTime = 0;
	Toast toast = null;
	boolean isUserWantToExit = false;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_scan_main);

		vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		
		tutorial_image = (ImageView) findViewById(R.id.tutorial_image);

		btn_check_connection = (Button) findViewById(R.id.btn_check_connection);
		btn_check_connection.setOnClickListener(onClickListener);

		//타이틀바 세팅
		titleBar = (RelativeLayout)findViewById(R.id.inc_title_bar);
		btn_TopLeft = (ImageButton)titleBar.findViewById(R.id.btn_top_left);
		btn_TopLeft.setOnClickListener(onClickListener);
		btn_TopRight = (ImageButton)titleBar.findViewById(R.id.btn_top_right);
		btn_TopRight.setVisibility(View.GONE);
		txt_subTitle = (TextView)findViewById(R.id.txt_subTitle);
		txt_subTitle.setText(getString(R.string.subTitle_scan_main));
		
		
		//탭 세팅--------------------------
		tabMenu = (LinearLayout)findViewById(R.id.inc_tab_menu);
		tab_measure = (ImageButton)findViewById(R.id.tab_measure);
		tab_measure.setImageDrawable(getResources().getDrawable(R.drawable.tab_measure_1));
		tab_record = (ImageButton)findViewById(R.id.tab_record);
		tab_user = (ImageButton)findViewById(R.id.tab_user);
		tab_help = (ImageButton)findViewById(R.id.tab_help);
		
		tab_record.setOnClickListener(onClickListener);
		tab_user.setOnClickListener(onClickListener);
		tab_help.setOnClickListener(onClickListener);
		//탭 세팅 끝--------------------------
		
		
		
		cTimer.start();
		isTimerRun = true;

		// BraodcastReceiver
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_HEADSET_PLUG);
		registerReceiver(mBroadcastReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		unregisterReceiver(mBroadcastReceiver);
	}

	/**
	 * 사용 안내를 나타낼 타이머
	 */
	CountDownTimer cTimer = new CountDownTimer(Long.MAX_VALUE, 1000) {

		long count = 0;

		@Override
		public void onTick(long millisUntilFinished) {

			count++;
			if (count % 2 == 0) {
				tutorial_image.setImageDrawable(getResources().getDrawable(
						R.drawable.measure_main_6));
			} else {
				tutorial_image.setImageDrawable(getResources().getDrawable(
						R.drawable.measure_main_7));
			}
		}

		@Override
		public void onFinish() {
			//Nothing
		}
	};
	
	
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			return exitApp();
		}

		return super.onKeyDown(keyCode, event);
	}

	View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_check_connection:
				if (headSetState == 1 && hasMicrophone == 1) {
					EnableDevice enableDevice = new EnableDevice();
					if(enableDevice.getEnableAScan(Build.MODEL) == true) {
						Log.e("DJKD", "dd??:"+enableDevice.getEnableAScan(Build.MODEL));
						Log.e("DJKD", "MODEL:"+Build.MODEL);
						moveToScan();
					} else {
						//지원 가능한 기기가 아닐 경우
						AlertDialog.Builder alert = new AlertDialog.Builder(AC_Scan_main.this);
						alert.setTitle("죄송합니다");
						alert.setMessage("본 기기에는 A-Scan이 최적화되지 않았습니다.\n이후에 나타나는 결과들은 신뢰할 수 없습니다.\n향후 업데이트를 통해 지원 대상 기기를 확장하는 중 입니다.");
						alert.setPositiveButton(getString(R.string.dialog_OK), new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								moveToScan();
							}
						});
						alert.show();
					}
				} else {
					long[] pattern = new long[4];
					pattern[0] = 0;
					pattern[1] = 100;
					pattern[2] = 50;
					pattern[3] = 200;
					vibe.vibrate(pattern, -1);
				}
				break;
			case R.id.btn_top_left:
				exitApp();
				break;
				
			//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
			case R.id.tab_record:
				startActivity(new Intent(AC_Scan_main.this, AC_RecordMain.class));
				finish();
				break;
			case R.id.tab_user:
				startActivity(new Intent(AC_Scan_main.this, AC_UserMain.class));
				finish();
				break;
			case R.id.tab_help:
				startActivity(new Intent(AC_Scan_main.this, AC_Help_main.class));
				finish();
				break;
			}
		}
	};
	
	private void moveToScan() {
		startActivity(new Intent(AC_Scan_main.this,
				AC_Warning.class));
		finish();
	}
	
	
	private boolean exitApp() {
		if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
			toast = Toast.makeText(this, getResources().getString(R.string.toast_exit), 2000);
			toast.show();
			this.lastBackPressTime = System.currentTimeMillis();
			return false;
		}
		else {
			if (toast != null) {
				toast.cancel();
			}

			isUserWantToExit = true;
			finish();
		}
		return true;
	}

	private void checkConnection() {
		//AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		// Log.i("smardi.Epi", "Wire connection:" + am.isWiredHeadsetOn());

		if (headSetState == 1 && hasMicrophone == 1) {
			btn_check_connection
					.setText(getString(R.string.scanMain_start_ascan));
			btn_check_connection.setBackgroundDrawable(getResources()
					.getDrawable(R.drawable.c_btn_start_ascan));
			btn_check_connection.setTextColor(Color.rgb(0xff, 0xff, 0xff));
			btn_check_connection.setShadowLayer(1, 1, 1, Color.rgb(0x33, 0x33, 0x33));
			tutorial_image.setImageDrawable(getResources().getDrawable(R.drawable.measure_main_8));
			
			if(isTimerRun == true) {
				cTimer.cancel();
				isTimerRun = false;
			}
			
		} else {
			btn_check_connection
					.setText(getString(R.string.scanMain_connect_ascan));
			btn_check_connection.setBackgroundDrawable(getResources()
					.getDrawable(R.drawable.c_btn_check_connection));
			btn_check_connection.setTextColor(Color.rgb(0x58, 0x59, 0x5B));
			btn_check_connection.setShadowLayer(0, 0, 0, Color.rgb(0x33, 0x33, 0x33));
			if(isTimerRun == false) {
				cTimer.start();
				isTimerRun = true;
			}
		}
	}

	BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				/**
				 * headSetState 0: 뽑혔을 때 1: 꽂혀있을 때
				 */

				headSetState = intent.getIntExtra("state", 0);
				hasMicrophone = intent.getIntExtra("microphone", 0);
				//Log.e("Epi", "MIC:" + hasMicrophone);
				checkConnection();

			}
		}
	};
}
